import os
import subprocess
from datetime import datetime

class GitAutomation:
    """Git自动化工具类，处理代码提交、推送等操作"""
    
    def __init__(self, repo_path: str = "."):
        self.repo_path = repo_path
        self._check_repo()
    
    def _check_repo(self):
        """检查是否为Git仓库"""
        try:
            subprocess.run(
                ["git", "rev-parse", "--is-inside-work-tree"],
                cwd=self.repo_path,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
        except subprocess.CalledProcessError:
            raise ValueError(f"{self.repo_path} 不是Git仓库")
    
    def commit_changes(self, message: str = None):
        """提交所有更改"""
        if not message:
            message = f"自动提交: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        
        # 添加所有更改
        subprocess.run(["git", "add", "."], cwd=self.repo_path, check=True)
        
        # 提交
        result = subprocess.run(
            ["git", "commit", "-m", message],
            cwd=self.repo_path,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        if result.returncode != 0:
            if "nothing to commit" in result.stderr:
                print("没有需要提交的更改")
                return False
            raise Exception(f"提交失败: {result.stderr}")
        
        print(f"提交成功: {message}")
        return True
    
    def push_changes(self, branch: str = "main"):
        """推送到远程仓库"""
        try:
            subprocess.run(
                ["git", "push", "origin", branch],
                cwd=self.repo_path,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            print(f"已推送到远程分支 {branch}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"推送失败: {e.stderr}")
            return False
    
    def auto_sync(self, commit_msg: str = None):
        """自动同步流程：拉取->提交->推送"""
        try:
            # 先拉取最新代码
            subprocess.run(
                ["git", "pull", "origin", "main"],
                cwd=self.repo_path,
                check=True
            )
            
            # 提交本地更改
            self.commit_changes(commit_msg)
            
            # 推送
            self.push_changes()
            return True
        except Exception as e:
            print(f"自动同步失败: {str(e)}")
            return False